<?php

namespace App\Http\Controllers;

use App\Models\TaskCount;
use App\Models\TaskLog;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 状态转换
     * @param $data
     * @param array $map
     * @return mixed
     */

    protected function stateToText(&$data, $map = []){
        foreach ($data as $key => &$row) {
            if(isset($row['share_count']) && isset($row['view']) && $row['share_count'] > 0){
                $row['per'] =  ((string)floor(($row['share_count']/$row['view'])*10000)/100).'%';
            }
            foreach ($map as $col => $pair) {
                if (isset($row[$col]) && isset($pair[$row[$col]])) {
                    $text = $col . '_text';
                    $row[$text] = $pair[$row[$col]];
                }
            }
        }
        return $data;
    }

    /**
     * 返回提示信息
     * @param int $code 0正常；1错误
     * @param string $msg 提示信息 default:success
     * @param array $data 数据
     * @return \Illuminate\Http\JsonResponse
     */
    protected function returnJson($code = 0,$msg = '',$data = []){
        $return = [
            'code' => $code,
            'msg'  => empty($msg) ? 'success' : $msg,
            'data' => $data
        ];
        return response()->json($return);
    }


    /**
     * 解析视频地址
     * @param $url 视频地址
     * @return string
     */
    protected function getVideo($url){
        //获取腾讯视频真实地址
        if (strstr($url, 'v.qq.com')) {
            //匹配腾讯链接拿到所需的vid
            $result = preg_match_all('/\/([0-9a-zA-Z]+).html/', $url, $matchs);
            if ($result) {
                $matchs = array_flatten($matchs);
            }
            $vid = $matchs[1] ?? '';
            if($vid){
                //1080P-fhd，超清-shd，高清-hd，标清-sd
                //http://vv.video.qq.com/getinfo?vids=v00149uf4ir&otype=json&charge=0&defaultfmt=shd    &defnpayver=1&appver=3.2.19.333
                $murl = 'http://vv.video.qq.com/getinfo?vids=' . $vid . '&platform=101001&charge=0&otype=json&defn=sd';
                $res = $this->httpsRequest($murl);
                $res = str_replace('QZOutputJson=', '', $res);
                $res = rtrim($res, ";");
                $res = json_decode($res, true);
                if (isset($res['msg']) && $res['msg'] == 'vid is wrong') {
                    return false;
                }
                $url = $res['vl']['vi'][0]['ul']['ui'][0]['url'];
                $fn = $res['vl']['vi'][0]['fn'];
                $fvkey = $res['vl']['vi'][0]['fvkey'];
                $return = [
                    'time' => date('i:s',$res['preview']),
                    'link' => $url . $fn . '?vkey=' . $fvkey
                ];
                return $return;
            }
        }
        return false;
    }

    /**
     * curl 请求
     * @param $url
     * @param null $data
     * @return mixed
     */
    protected function httpsRequest($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, true);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    /**
     * 任务更新
     * @param int $uid 用户ID
     * @param string $task_type 任务类型
     * @param int $param_id 参数ID
     */
    protected function finishTask($uid = 0,$task_type = '',$param_id = 0){
        if(!$task_type){
            return false;
        }
        if($param_id > 0){
            $isLoged = TaskLog::where(['user_id'=>$uid,'task_type'=>$task_type,'param_id' => $param_id])
                ->where('created_at','>=',Carbon::today())
                ->first();
            if($isLoged){
                return false;
            }
        }
        DB::transaction(function () use($uid,$task_type,$param_id){
            $taskModel = new TaskCount();
            $reData = $taskModel->updateCount($uid,$task_type);
            if($reData){
                (new Users())->updateTaskScore($uid,$task_type,$reData[$task_type]);
                (new TaskLog())->updateLog($uid,$task_type,$reData[$task_type],$param_id);
            }
        });
        return true;
    }


    /**
     * 订单ID算法
     * @return string
     */
    protected function build_order_no()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

}
